package com.lingshu.app.repository;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.lingshu.app.config.App;
import com.lingshu.app.database.bean.UserBean;
import com.lingshu.app.network.CustomDisposable;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.Completable;
import io.reactivex.Flowable;

/**
 * 用户数据提供
 *
 * @author yudingjin
 */
public class UserRepository {
    private static final String TAG = UserRepository.class.getSimpleName();
    public final MutableLiveData<String> failed = new MutableLiveData<>();
    private final MutableLiveData<UserBean> userMutableLiveData = new MutableLiveData<>();

    @Inject
    UserRepository() {
    }

    public MutableLiveData<UserBean> getUser() {
        Flowable<List<UserBean>> listFlowable = App.getDb().userDao().getAll();
        CustomDisposable.addDisposable(listFlowable, users -> {
            if (users.size() > 0) {
                for (UserBean user : users) {
                    if (user.getUid() == 1) {
                        userMutableLiveData.postValue(user);
                        break;
                    }
                }
            } else {
                failed.postValue("你还没有注册过吧，去注册吧！");
            }
        });
        return userMutableLiveData;
    }

    /**
     * 更新用户信息
     *
     * @param user
     */
    public void updateUser(UserBean user) {
        Completable update = App.getDb().userDao().update(user);
        CustomDisposable.addDisposable(update, () -> {
            Log.d(TAG, "updateUser: " + "保存成功");
            failed.postValue("200");
        });
    }

    /**
     * 保存用户
     */
    public void saveUser(UserBean user) {
        Completable deleteAll = App.getDb().userDao().deleteAll();
        CustomDisposable.addDisposable(deleteAll, () -> {
            //保存到数据库
            Completable insertAll = App.getDb().userDao().insert(user);
            //RxJava处理Room数据存储
            CustomDisposable.addDisposable(insertAll, () -> failed.postValue("200"));
        });
    }

    public Boolean login(String account, String password) {
        if (account.equals("admin") && password.equals("admin")) {
            return true;
        }
        return false;
    }
}